package club.kynb.mall.application.flow.order;

import club.kynb.mall.application.context.OrderSubmitContext;
import club.kynb.mall.application.model.model.dto.PreviewOrderDTO;
import club.kynb.mall.application.model.model.dto.PreviewOrderDetailDTO;
import club.kynb.mall.application.model.model.dto.PreviewOrderSkuDTO;
import club.kynb.mall.application.model.model.dto.PreviewOrderSpuDTO;
import club.kynb.mall.order.constant.OrderSubmitStatusEnum;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author kynb_club@163.com
 * @since 2021/7/7 1:56 下午
 * Distribution distance
 */
@Slf4j
@Component
@AllArgsConstructor
public class CheckWarehouseStockFilter extends AbstractSubmitOrderFlowFilter {

    @Override
    protected void doService(OrderSubmitContext orderSubmitContext) {
        boolean checkStock = checkStock(orderSubmitContext);
        if (!checkStock) {
            log.error("库存校验失败，没有找到库存充足的仓库，商品信息：{}", JSONUtil.toJsonStr(orderSubmitContext.getOrderSubmitResultVO().getStockLessList()));
            orderSubmitContext.setFastFailed(true);
            orderSubmitContext.getOrderSubmitResultVO().setSubmitStatus(OrderSubmitStatusEnum.FAILED.getStatus());
            orderSubmitContext.getOrderSubmitResultVO().setFailureReason("库存不足");
        }
    }

    private boolean checkStock(OrderSubmitContext orderSubmitContext) {
        final PreviewOrderDTO previewOrder = orderSubmitContext.getPreviewOrder();
        final List<PreviewOrderSpuDTO> stockLessList = orderSubmitContext.getOrderSubmitResultVO().getStockLessList();
        final List<PreviewOrderDetailDTO> orderDetailList = previewOrder.getOrderDetailList();
        boolean allOk = true;
        //验证是否所有商品都有库存
        for (PreviewOrderDetailDTO previewOrderDetailDTO : orderDetailList) {
            final PreviewOrderSpuDTO previewOrderSpuDTO = previewOrderDetailDTO.getPreviewOrderSpuDTO();
            final PreviewOrderSkuDTO previewOrderSkuDTO = previewOrderSpuDTO.getPreviewOrderSkuDTO();
            final String skuId = previewOrderSkuDTO.getId();
            final Integer skuNum = previewOrderSkuDTO.getSkuNum();
            boolean ok = true;
            if (!ok) {
                log.warn("提交订单，库存不足 skuId: {}  需要库存数量：{}",  skuId, skuNum);
                stockLessList.add(previewOrderSpuDTO);
                allOk = false;
                break;
            }
        }
        if (allOk) {
            return true;
        }
        log.warn("提交订单，库存检查失败!!! \n 订单的商品信息：{}", orderDetailList);
        return false;
    }
}
